package book

import (
	"NovelBook/dao"
	"NovelBook/models/db_models"
	"strings"
)

func SearchFaintly(query string) ([]db_models.Books, error) {
	var books []db_models.Books
	query = strings.Replace(query, "%", "\\%", -1)
	err := dao.GetDb().Where("name LIKE ? or author LIKE ? or publisher LIKE ?", "%"+query+"%", "%"+query+"%", "%"+query+"%").Find(&books).Error
	if err != nil {
		return nil, err
	}
	for i, book := range books {
		if book.Name == query {
			// 将匹配到的书名移到数组开头
			copy(books[1:i+1], books[0:i])
			books[0] = book
			break
		}
	}
	return books, nil
}
